package com.example.yangxu0703.thundermapclient.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import java.io.IOException;
import java.util.Set;

import static com.example.yangxu0703.thundermapclient.bluetooth.AbsBluetooth.DISCONNECT;

public class AccpetThread extends Thread {

    private BluetoothAdapter adapter;
    private BluetoothDevice device;
    private BluetoothServerSocket ServerSocket;
    private BluetoothSocket socket;
    private AbsBluetooth.Listerner listerner;


    AccpetThread(BluetoothAdapter adapter) {
        this.adapter = adapter;
        try {
            Set<BluetoothDevice> deviceConllection = adapter.getBondedDevices();
            for (BluetoothDevice devices : deviceConllection) {
                device = devices;
            }
            ServerSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(device.getName(), AbsBluetooth.uuid);
        } catch (IOException e) {
            closeconnection();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                socket = ServerSocket.accept();
            } catch (IOException e) {
                closeconnection();
            }

            if (socket.isConnected()) {
                ReciveMsg reciveMsg = new ReciveMsg(socket);
                reciveMsg.start();
                reciveMsg.setListerner(new AbsBluetooth.Listerner() {
                    @Override
                    public void observerConnection(int status) {
                        listerner.observerConnection(status);
                    }
                    @Override
                    public void backMessage(String msg) {
                        listerner.backMessage(msg);
                    }
                });
            }
        }
    }

    private void closeconnection() {
        try {
            Log.i("CON_STATE", "Failed!");
            socket.close();
            socket = null;
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    public void setListerner(AbsBluetooth.Listerner listerner){
		this.listerner=listerner;
	}
}
